package com.cy.阿里上机测试.Test01;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * //1 多线程交叉打印
 * 建立三个线程,线程名字分别为:A、B、C，要求三个线程分别打印自己的线程名字,但是要求三个线程同时运行，并且实现交替打印，
 * 即按照ABCABCABC的顺序打印。打印10轮，打印完毕控制台输出字符串:"打印完毕"
 *
 * @author chen_yu
 * @date 2021/1/19 22:25
 */
public class Test {

    private static int state = 0;

    private static Lock lock = new ReentrantLock();

    private static CountDownLatch countDownLatch = new CountDownLatch(30);


    static class MyThread extends Thread {
        private final int printState;
        private final Condition waitCondition;
        private final Condition notifyCondition;

        public MyThread(String name, int printState, Condition waitCondition, Condition notifyCondition) {
            super(name);
            this.printState = printState;
            this.waitCondition = waitCondition;
            this.notifyCondition = notifyCondition;
        }

        @SneakyThrows
        @Override
        public void run() {
            for (int i = 0; i < 10; ) {
                lock.lock();
                try {
                    while (state % 3 != printState) {
                        waitCondition.await();
                    }
                    System.out.print(Thread.currentThread().getName());
                    state++;
                    i++;
                    notifyCondition.signal();
                } finally {
                    lock.unlock();
                    countDownLatch.countDown();
                }

            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();
        Condition conditionC = lock.newCondition();
        MyThread threadA = new MyThread("A", 0, conditionA, conditionB);
        MyThread threadB = new MyThread("B", 1, conditionB, conditionC);
        MyThread threadC = new MyThread("C", 2, conditionC, conditionA);
        threadA.start();
        threadB.start();
        threadC.start();
        countDownLatch.await();
        System.out.println("\n打印完毕");

    }

}
